package login

import (
	"fmt"
	"ginweb-admin/commons/jwtgo"
	"ginweb-admin/commons/response"
	"ginweb-admin/global"
	"ginweb-admin/model/entity/jwt"
	"github.com/gin-gonic/gin"
)

type LogoutAPi struct{}

var jwtService = jwtgo.JwtService{}

// 退出登录
func (api *LogoutAPi) Logout(c *gin.Context) {
	// 获取token
	token := c.GetHeader("Authorization")
	if token == "" {
		response.Fail(4001, "请求未携带token，无访问权限！", c)
		return
	}

	// 挤下线的时候清空本地缓存
	customClaims, _ := jwtgo.GetClaims(c)
	global.Cache.Delete(fmt.Sprintf("LocalCache:Login:%d", customClaims.UserId))

	// 把token加入黑名单
	err := jwtService.JsonInBlacklist(jwt.JwtBlacklist{Jwt: token})
	if err != nil {
		response.Fail(4001, "token作废失败，没有进入黑名单！", c)
		return
	}

	// 退出成功
	response.Ok("退出登录成功，请重新登录！", c)

}
